<template>
	<view class="wechat-login-container">
		<view class="header">
			<image class="logo" src="/static/logo.svg" mode="aspectFit"></image>
			<text class="title">brainCube</text>
			<text class="subtitle">智能测试平台</text>
		</view>
		
		<view class="login-content">
			<view class="welcome-text">
				<text class="welcome-title">欢迎使用微信登录</text>
				<text class="welcome-desc">快速登录，开始您的智能测试之旅</text>
			</view>
			
			<view class="login-buttons">
				<BrandButton 
					:loading="isLoading"
					:disabled="isLoading"
					:text="isLoading ? '登录中...' : '🔐 微信登录'"
					type="primary" 
					size="large"
					@click="handleWechatLogin"
				></BrandButton>
				
				<view class="divider">
					<view class="line"></view>
					<text class="divider-text">或</text>
					<view class="line"></view>
				</view>
				
				<BrandButton 
					text="👤 游客模式"
					type="outline" 
					size="large"
					@click="handleGuestLogin"
				></BrandButton>
			</view>
			
			<view class="features">
				<view class="feature-item">
					<text class="feature-icon">🧠</text>
					<text class="feature-text">智能测试</text>
				</view>
				<view class="feature-item">
					<text class="feature-icon">📊</text>
					<text class="feature-text">数据分析</text>
				</view>
				<view class="feature-item">
					<text class="feature-icon">🏆</text>
					<text class="feature-text">排行榜</text>
				</view>
			</view>
		</view>
		
		<view class="footer">
			<view class="agreement-section">
				<view class="checkbox-container" @click="toggleAgreement">
					<view class="checkbox" :class="{ checked: agreedToTerms }">
						<text v-if="agreedToTerms" class="checkmark">✓</text>
					</view>
					<view class="agreement-text">
						<text class="footer-text">我已阅读并同意</text>
						<text class="link" @click.stop="showPrivacyPolicy">《隐私政策》</text>
						<text class="footer-text">和</text>
						<text class="link" @click.stop="showUserAgreement">《用户协议》</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { wechatLogin } from '@/utils/authManager.js'
import { logInfo, logError } from '@/utils/errorHandler.js'
import { hasAgreedAllAgreements } from '@/utils/agreementManager.js'
import BrandButton from '@/components/BrandButton.vue'

// 响应式数据
const isLoading = ref(false)
const agreedToTerms = ref(false)
// 生命周期
uni.onLoad(() => {
	// 检查是否已经登录
	checkLoginStatus()
	// 检查是否已同意协议
	if (hasAgreedAllAgreements()) {
		agreedToTerms.value = true
	}
})

// 方法定义
		/**
		 * 切换协议同意状态
		 */
		const toggleAgreement = () => {
			agreedToTerms.value = !agreedToTerms.value
		}
		
		/**
		 * 检查登录状态
		 */
		const checkLoginStatus = () => {
			try {
				const userInfo = uni.getStorageSync('user_info')
				if (userInfo && userInfo.id) {
					// 已登录，跳转到首页
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}
			} catch (error) {
				logError('检查登录状态失败', { error: error.message })
			}
		},
		
		/**
		 * 处理微信登录
		 */
		const handleWechatLogin = async () => {
			if (isLoading.value) return
			
			// 检查是否已勾选同意协议
			if (!agreedToTerms.value) {
				uni.showToast({
					title: '请先勾选同意协议',
					icon: 'none',
					duration: 2000
				})
				return
			}
			
			// 检查是否已同意所有协议
			if (!hasAgreedAllAgreements()) {
				uni.showModal({
					title: '提示',
					content: '请先阅读并同意隐私政策和用户协议',
					confirmText: '去阅读',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/agreement-check/agreement-check'
							})
						}
					}
				})
				return
			}
			
			isLoading.value = true
			
			try {
				// 调用微信登录API
				const loginResult = await this.getWechatLoginCode()
				
				if (loginResult.code) {
					// 获取用户信息
					const userInfo = await this.getWechatUserInfo()
					
					// 调用后端微信登录接口
					const user = await wechatLogin({
						code: loginResult.code,
						userInfo: userInfo
					})
					
					logInfo('微信登录成功', { userId: user.id, nickname: user.nickname })
					
					// 显示成功提示
					uni.showToast({
						title: '登录成功',
						icon: 'success',
						duration: 2000
					})
					
					// 延迟跳转到首页
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}, 1500)
				} else {
					throw new Error('获取微信授权码失败')
				}
			} catch (error) {
				logError('微信登录失败', { error: error.message })
				
				uni.showToast({
					title: error.message || '登录失败',
					icon: 'none',
					duration: 3000
				})
			} finally {
				isLoading.value = false
			}
		}
		
		/**
		 * 获取微信登录授权码
		 */
		const getWechatLoginCode = () => {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: (result) => {
						resolve(result)
					},
					fail: (error) => {
						reject(new Error('微信登录授权失败: ' + error.errMsg))
					}
				})
			})
		},
		
		/**
		 * 获取微信用户信息
		 */
		const getWechatUserInfo = () => {
			return new Promise((resolve, reject) => {
				uni.getUserInfo({
					provider: 'weixin',
					success: (result) => {
						resolve(result.userInfo)
					},
					fail: (error) => {
						reject(new Error('获取用户信息失败: ' + error.errMsg))
					}
				})
			})
		},
		
		/**
		 * 处理游客登录
		 */
		const handleGuestLogin = () => {
			// 检查是否已勾选同意协议
			if (!agreedToTerms.value) {
				uni.showToast({
					title: '请先勾选同意协议',
					icon: 'none',
					duration: 2000
				})
				return
			}
			
			// 检查是否已同意所有协议
			if (!hasAgreedAllAgreements()) {
				uni.showModal({
					title: '提示',
					content: '请先阅读并同意隐私政策和用户协议',
					confirmText: '去阅读',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/agreement-check/agreement-check'
							})
						}
					}
				})
				return
			}
			
			// 设置游客模式
			uni.setStorageSync('user_mode', 'guest')
			
			uni.showToast({
				title: '进入游客模式',
				icon: 'success',
				duration: 2000
			})
			
			// 跳转到首页
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			}, 1500)
		}
		
		/**
		 * 显示隐私政策
		 */
		const showPrivacyPolicy = () => {
			uni.navigateTo({
				url: '/pages/privacy-policy/privacy-policy'
			})
		},
		
		/**
		 * 显示用户协议
		 */
		const showUserAgreement = () => {
			uni.navigateTo({
				url: '/pages/user-agreement/user-agreement'
			})
		}
</script>

<style lang="scss" scoped>

.wechat-login-container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background: linear-gradient(135deg, $brand-primary-light 0%, $bg-secondary 100%);
	padding: 40rpx 60rpx;
	box-sizing: border-box;
	
	// 响应式适配
	@media screen and (max-width: 750rpx) {
		padding: 30rpx 40rpx;
	}
}

.header {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-top: 120rpx;
	margin-bottom: 80rpx;
	
	.logo {
		width: 120rpx;
		height: 120rpx;
		margin-bottom: 30rpx;
		border-radius: 24rpx;
		box-shadow: 0 8rpx 32rpx rgba($brand-primary, 0.2);
	}
	
	.title {
		font-size: 48rpx;
		font-weight: 700;
		color: $brand-primary-dark;
		margin-bottom: 16rpx;
		letter-spacing: 2rpx;
	}
	
	.subtitle {
		font-size: 28rpx;
		color: $text-secondary;
		font-weight: 400;
	}
}

.login-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.welcome-text {
	text-align: center;
	margin-bottom: 80rpx;
	
	.welcome-title {
		display: block;
		font-size: 36rpx;
		font-weight: 600;
		color: $text-primary;
		margin-bottom: 20rpx;
	}
	
	.welcome-desc {
		display: block;
		font-size: 28rpx;
		color: $text-secondary;
		line-height: 1.5;
	}
}

.login-buttons {
		margin-bottom: 60rpx;
		display: flex;
		flex-direction: column;
		gap: 0;
		
		// 确保按钮全宽度显示
		:deep(.brand-button) {
			width: 100%;
			margin-bottom: 30rpx;
			padding: 30rpx 40rpx;
			font-size: 32rpx;
			border-radius: 50rpx;
			min-height: 100rpx;
			box-sizing: border-box;
		}
		
		.divider {
			display: flex;
			align-items: center;
			margin: 20rpx 0 30rpx 0;
			
			.line {
				flex: 1;
				height: 2rpx;
				background: $border-light;
			}
			
			.divider-text {
				padding: 0 24rpx;
				font-size: 24rpx;
				color: $text-tertiary;
			}
		}
	}

.features {
	display: flex;
	justify-content: space-around;
	margin-bottom: 40rpx;
	
	.feature-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 16rpx;
		
		.feature-icon {
			font-size: 40rpx;
		}
		
		.feature-text {
			font-size: 24rpx;
			color: $text-secondary;
			font-weight: 500;
		}
	}
}

.footer {
	text-align: center;
	padding: 40rpx 0;
	margin-top: auto;
	
	.agreement-section {
		display: flex;
		justify-content: center;
		align-items: center;
		
		.checkbox-container {
			display: flex;
			align-items: center;
			gap: 16rpx;
			cursor: pointer;
			padding: 10rpx;
			border-radius: 8rpx;
			transition: background-color 0.2s ease;
			
			&:hover {
				background-color: rgba($brand-primary, 0.05);
			}
			
			.checkbox {
				width: 32rpx;
				height: 32rpx;
				border: 2rpx solid $border-light;
				border-radius: 6rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				transition: all 0.2s ease;
				background-color: white;
				flex-shrink: 0;
				
				&.checked {
					background-color: $brand-primary;
					border-color: $brand-primary;
					
					.checkmark {
						color: white;
						font-size: 20rpx;
						font-weight: bold;
					}
				}
			}
			
			.agreement-text {
				display: flex;
				flex-wrap: wrap;
				align-items: center;
				gap: 4rpx;
				
				.footer-text {
					font-size: 24rpx;
					color: $text-tertiary;
				}
				
				.link {
					font-size: 24rpx;
					color: $brand-primary;
					text-decoration: underline;
					margin: 0 4rpx;
					transition: color 0.2s ease;
					
					&:hover {
						color: $brand-primary-dark;
					}
				}
			}
		}
	}
}
</style>